<template>
 <div class="configManage">
    <a-breadcrumb separator=">" style="margin-bottom: 16px;">
      <a-breadcrumb-item><a href="#" @click="handleClickHistoryBackFun">项目管理</a></a-breadcrumb-item>
      <a-breadcrumb-item>组态配置</a-breadcrumb-item>
    </a-breadcrumb>
    <a-row>
      <a-col :span="24">
        <a-card :bordered="false">
          <template #title>
            <span style="margin-right: 14px;">组态管理列表</span>
            <a-button style="float: right;" @click="handleAddFun" class="customBut customQueryBut">新增</a-button>
          </template>
          <div class="ownTable">
            <a-table
              bordered
              class="userInfoTable"
              :columns="configColumns"
              :data-source="configData"
              :pagination="pagination"
              @change="handleTableChange"
            >
              <template #bodyCell="{ column, text, record }">
                <template v-if="column.dataIndex === 'createTime'">
                  {{ text === null ? '' : ConvertToDateFun(text, "yyyy-MM-dd HH:mm:ss") }}
                </template>
                <template v-else-if="column.dataIndex === 'operate'">
                  <span title="修改" class="operateSapn" @click="handleClickExitFun(record)">修改</span>
                  <span title="编辑组态" class="operateSapn" @click="handleClickEditFun(record)">编辑</span>
                  <span title="预览组态" class="operateSapn" @click="handleClickPreviewFun(record)">预览</span>
                  <span title="导出组态" class="operateSapn" @click="handleClickExportFun(record)">导出</span>
                  <a-popconfirm
                    :title="'确定要删除当前组态吗？'"
                    @confirm="handleClickDelFun(record)"
                  >
                    <span title="删除" class="operateSapn" >删除</span>
                  </a-popconfirm>
                </template>
              </template>
            </a-table>
          </div>
        </a-card>
      </a-col>
    </a-row>
 </div>
<AddAndExitTopology ref="addAndExitTopologyRef" @loadConfigListsFun="loadConfigListsFun" />
<EditTopology ref="editTopologyRef" @loadConfigListsFun="loadConfigListsFun" />
<PreviewTopology ref="previewTopologyRef" />



</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  import { storeToRefs } from 'pinia';
  import { useUserStore } from '@/store/user';
  import { useRouterStore } from '@/store/router';
  import { message } from 'ant-design-vue';
  import { ConvertToDateFun } from '@/utils/secret';
  import { List, GetById, DeleteTopology } from '@/api/index';
  import { otherEncryptFun } from '@/utils/secret';
  import { customRequest } from "@/utils/otherRequest";
  import FileSaver from 'file-saver';
  import AddAndExitTopology from '@/components/web/modal/addAndExitTopology.vue'
  import EditTopology from '@/components/web/modal/editTopology.vue'
  import PreviewTopology from '@/components/web/modal/previewTopology.vue'


  const userStore = useUserStore();
  const routerStore = useRouterStore();
  const { activeProjectId, activeProjectList } = storeToRefs(routerStore);
  const { otherServerToken } = storeToRefs(userStore);

  
  const addAndExitTopologyRef = ref(null);
  const editTopologyRef = ref(null);
  const previewTopologyRef = ref(null);

  const configColumns = ref<any[]>([
    {
        title: "操作",
        align: "center",
        dataIndex: 'operate',
        checked: true,
        width: 240,
        fixed: 'left',
    },
    {
        title: '配置名称',
        dataIndex: 'name',
        align: "center",
    },
    {
        title: '类型',
        dataIndex: 'type',
        align: "center",
    },
    {
        title: '配置描述',
        dataIndex: 'description',
        align: "center",
    },
    {
        title: '创建时间',
        dataIndex: 'createTime',
        align: "center",
    },
    {
        title: '更新时间',
        dataIndex: 'updateTime',
        align: "center",
    },
  ]);
  const configData = ref<any[]>([]);
  const pagination = reactive({
    total: 0,
    current: 1,
    pageSize: 10,
    showSizeChanger: true,
    pageSizeOptions: ['10', '20', '40'],
  });
  const handleTableChange = (page:any) => {
    pagination.current = page.current;
    pagination.pageSize = page.pageSize;
  }
  onMounted(() => {
    loadConfigListsFun();
    handleFun();
  })
  const loadConfigListsFun = async () => {
    const res = await List({
      size: pagination.pageSize,
      current: pagination.current,
      projectId: activeProjectId.value,
    });
    if(res) {
      if(res.code === 1000) {
        configData.value = res.data.records;
        pagination.total = res.data.total;
      } else {
        message.error(res.msg);
      }
    }
  }

  const handleClickHistoryBackFun = () => {
    activeProjectId.value = null;
    activeProjectList.value = null;
    otherServerToken.value = '';
    window.history.back();
  }

  const handleAddFun = () => {
    addAndExitTopologyRef.value.showModal();
  }
  const handleClickExitFun = (record: any) => {
    addAndExitTopologyRef.value.showModal(record);
  }
  const handleClickEditFun = (record: any) => {
    editTopologyRef.value.showModal(record);
  }
  const handleClickPreviewFun = (record: any) => {
    if(record.jsonContent === "{}") {
      message.error("组态为空，无法预览");
      return;
    }
    previewTopologyRef.value.showModal(record);
  }
  const handleClickExportFun = (record: any) => {
    if(record.jsonContent === "{}") {
      message.error("组态为空，无法导出");
      return;
    }
    const data: any =JSON.parse(record.jsonContent);
    FileSaver.saveAs(
      new Blob([JSON.stringify(data)], {
        type: 'text/plain;charset=utf-8',
      }),
      `${record.name}_组态.json`
    );
  }
  const handleClickDelFun = async (record: any) => {
    const res = await DeleteTopology({
      topologyIds: record.id.toString(),
    });
    if(res) {
      if(res.code === 1000) {
        message.success(res.data);
        loadConfigListsFun();
      } else {
        message.error(res.msg);
      }
    }
  }

  const handleFun = async () => {
    const _publicKeyObj = activeProjectList.value.properties.find(item => item.name === 'publicKey');
    const _apiUrlObj = activeProjectList.value.properties.find(item => item.name === 'apiUrl');
    if(_publicKeyObj && _apiUrlObj) {
      const _publicKey = _publicKeyObj.value;
      const _apiUrl = _apiUrlObj.value;
      const res = await customRequest(
          _apiUrl+'user/auth',
          'POST',
          {
            data: await otherEncryptFun(_publicKey, '0.123.'+ new Date().getTime().toString())
          }
      );
      if(res) {
        if(res.code === 1000) {
          otherServerToken.value = res.data.token;
        } else {
          message.error(res.msg);
        }
      }

    }
  }
  

  
</script>

<style scoped>

</style>
